package com.ruicar.afs.cloud.afscase.mq.receiver.processor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfoTemp;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPoolHistory;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoTempService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolHistoryService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.WorkflowAppointVO;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.processor.enums.WorkflowType;
import com.ruicar.afs.cloud.afscase.processor.service.ReconsiderationWorkflowService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.vo.UserVo;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ComAttachmentFileDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ReconsiderationDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.seats.entity.UserCollocation;
import com.ruicar.afs.cloud.seats.service.UserCollocationService;
import com.ruicar.afs.cloud.seats.util.PostStatus;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 复议
 * @author xiaolong
 * @created 2020/08/03 15:45
 * @version 1.0
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit",name="enable")
public class ReconsiderationProcessor implements AfsMqBizProcessor<ReconsiderationDto> {

    private CaseBaseInfoService caseBaseInfoService;

    private WorkTaskPoolHistoryService historyService;

    private WorkProcessScheduleInfoTempService scheduleInfoTempService;

    private ReconsiderationWorkflowService reconsiderationWorkflowService;

    private ComAttachmentFileService comAttachmentFileService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processMessage(ReconsiderationDto entity){
        CaseBaseInfo baseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
        .eq(CaseBaseInfo::getApplyNo,entity.getApplyNo()));
        /**  解析影像文件ComAttachmentFile  **/
        ArrayList<ComAttachmentFile> comAttachmentFileArrayList = this.parseComAttachmentFile(entity);
        if(CollectionUtil.isNotEmpty(comAttachmentFileArrayList)) {
            comAttachmentFileService.saveOrUpdateBatch(comAttachmentFileArrayList, comAttachmentFileArrayList.size());
            log.info("影像文件add成功！！！");
        }
        List<WorkTaskPoolHistory> hisList=historyService.list(Wrappers.<WorkTaskPoolHistory>query().lambda()
                .eq(WorkTaskPoolHistory::getStageId,baseInfo.getNormalApproveFlowId())
                .eq(WorkTaskPoolHistory::getFirstNode, WhetherEnum.YES.getCode())
                .orderByDesc(WorkTaskPoolHistory::getCreateTime));
        //发起流程
        WorkflowAppointVO appointVO = new WorkflowAppointVO();
        if(CollectionUtils.isNotEmpty(hisList)){
                WorkProcessScheduleInfoTemp temp = new WorkProcessScheduleInfoTemp();
                temp.setAfsFlowKey(WorkflowType.RECONSIDER_APPLY.getAfsFlowKey());
                temp.setApplyNo(entity.getApplyNo());
                temp.setStartTime(new Date());
                scheduleInfoTempService.saveWithNewTransactional(temp);
                appointVO.setApplyNo(entity.getApplyNo());
                this.startReconsiderationFlowByPerson(temp,appointVO,entity.getReconReason());

        }else{
            log.info("复议流程未能发起:{}",entity.getApplyNo());
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
            return MqTransCode.AFS_POS_APPLY_CASE_CTM_ASSETS_RECONSIDERATION;
    }

    /**
     * @description:复议指定处理人
     * @author xiaolong
     * @created 2020/08/04 11:30
     * @version 1.0
     */
    public void startReconsiderationFlowByPerson(WorkProcessScheduleInfoTemp temp, WorkflowAppointVO appointVO,String reconReason){
        log.info("########################## 复议申请处理人流程发起 Start ###############");
        reconsiderationWorkflowService.startReconsideration(temp,reconReason);
        log.info("########################## 复议申请指定处理人流程发起 End###############");
    }

    /**
     * 影像资料解析
     * @param entity
     * @return
     */
    private ArrayList<ComAttachmentFile> parseComAttachmentFile(ReconsiderationDto entity ) {
        ArrayList<ComAttachmentFile> comAttachmentFileArrayList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entity.getComAttachmentFileListDto())) {
            for (ComAttachmentFileDto attachmentFileDto : entity.getComAttachmentFileListDto()) {
                if (org.springframework.util.ObjectUtils.isEmpty(attachmentFileDto.getBusiNo()) || org.springframework.util.ObjectUtils.isEmpty(attachmentFileDto.getBelongNo())) {
                    throw new AfsBaseException("业务编号:" + attachmentFileDto.getBusiNo() + ",所属业务编号:" + attachmentFileDto.getBelongNo() + "不能为空");
                }
                ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
                BeanUtils.copyProperties(attachmentFileDto, comAttachmentFile);
                comAttachmentFileArrayList.add(comAttachmentFile);

            }
        }
        return  comAttachmentFileArrayList;
    }
}
